package StorageComponents;

import Exceptions.InvalidArrayLengthException;

/**
 * 
 * This class represents the microprocessor's set of general purpose registers.
 * Each register can store 8 bits and all operations involve all 8 bits.
 * There are 8 general purpose registers in total, and they are implemented using
 * an Object type array of size 8, which stores integer type arrays of size 8 also.
 * 
 */
public class Registers {

	private Object[] registers;
	
	public Registers(){
		
		registers = new Object[8];
		for( int i = 0; i < registers.length; i++ ){
			registers[i] = new int[8];
		}
	}
	
	/**
	 * This method simulates reading a general purpose register 
	 * @param index the index belonging to the register that is to be read
	 * @return an array of the 8 integers (bits) read from the register
	 */
	public int[] read(int index) throws IndexOutOfBoundsException{
		
		if( index < 0 || index > 7 )
			throw new IndexOutOfBoundsException("Cannot ovewrite register. Expected 0 <= index <= 7. Received " +
					"index = " +index );
		
		return ( int[] ) registers[index];
	}
	
	/**
	 * This method simulates reading a general purpose register 
	 * @param data array of 8 bits to be stored in the register
	 * @param index the index belonging to the register that is to be read
	 * @return an array of the 8 integers (bits) read from the register
	 */
	public void write(int[] data, int index) throws InvalidArrayLengthException, IndexOutOfBoundsException{
		
		if( data.length != 8 )
			throw new InvalidArrayLengthException("Cannot overwrite register. Expected data.length = 8. Received +" +
					"data.length = " + data.length );
		if( index < 0 || index > 7 )
			throw new IndexOutOfBoundsException("Cannot ovewrite register. Expected 0 <= index <= 7. Received " +
					"index = " +index );
		int[] register = (int[]) registers[index];
		for( int i = 0; i < data.length; i++ )
			register[i] = data[i];
	}

}
